﻿using System;
using System.Reflection;

namespace RQX.Common.Web.Web.Container
{
    /// <summary>
    /// 反射类
    /// </summary>
    public class ReflectionObj
    {
        public readonly string FullName;
        public readonly string contextName;
        public ReflectionObj(string fullName)
        {
            FullName = fullName;
            contextName = fullName.Substring(0, fullName.IndexOf(".Domain.")) + ".Domain.PlugDbContext";
        }

        public object Invoke(string methodName, params object[] param)
        {
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();
            MethodInfo method = null;
            object instance = null;
            object dbinstance = null;


            foreach (var assembly in assemblies)
            {
                foreach (var type in assembly.GetTypes())
                {
                    if (type.FullName.Equals(contextName))
                    {
                        dbinstance = Activator.CreateInstance(type);
                        break;
                    }
                }
                if (dbinstance != null) break;
            }


            foreach (var assembly in assemblies)
            {
                foreach (var type in assembly.GetTypes())
                {
                    if (type.FullName.Equals(FullName))
                    {
                        method = type.GetMethod(methodName);
                        instance = Activator.CreateInstance(type, dbinstance);
                        break;
                    }
                }
                if (method != null) break;
            }
            return method?.Invoke(instance, param);
        }
    }
}
